#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
@File Name  : backupToUFile_WinSCP.py
@Author     : LeeCQ
@Date-Time  : 2019/12/12 23:10

"""
import os
import sys, logging

logger = logging.getLogger("logger")  # 创建实例
formatter = logging.Formatter("[%(asctime)s] < %(threadName)s: %(thread)d > [%(levelname)s] %(message)s")
# 终端日志
consle_handler = logging.StreamHandler(sys.stdout)
consle_handler.setFormatter(formatter)  # 日志文件的格式
logger.setLevel(logging.DEBUG)  # 设置日志文件等级
logger.addHandler(consle_handler)  #


class BackupToUFile:
    """利用WinSCP的接口，备份文件到UFile - FTP

    实现：构造字符串；通过cmd命令行实现文件的备份。
    字符串包括:
    :param WinSCP_exe:
    :param
    """
    WinSCP_exe = r'"C:\Program Files (x86)\WinSCP\WinSCP.exe" '  # 双引号是必须的；
    console = '/console '  # 启用控制台命令
    command = '/command '  # 命令操作
    open_ftp = r'"open ftp://leecq%2Fufile-test:Fp1ta0JPi9hFgBtNgd6J2wnS0VLL08IP@box.u-file.cn/" '
    option_batch_continue = '"option batch continue" '  # 批处理模式
    option_transfer_binary = '"option transfer binary" '  # 二进制传输方式；
    option_3 = ' '

    synchronize_remote = 'synchronize remote '  # 文件同步到远程

    def __init__(self, synchronize: list or tuple, _log=None, log_level=None):
        self.synchronize_list = synchronize
        self.log = ' ' if not _log else f'/log={_log} '
        self.log += ' ' if not log_level else f'/loglevel={str(log_level)} '

        self.cmd_exe = ' '.join((self.WinSCP_exe, self.log, self.command, self.open_ftp))

    @staticmethod
    def __cmd(cmd):
        return os.popen(cmd).read()

    def _cmd(self, command):
        _c = self.cmd_exe
        _c += command + ' ' + self.option_transfer_binary
        _c += '  "exit"'
        print(_c)
        return self.__cmd(_c)

    def structure_synchronize(self):
        return ' '.join([f'\"{self.synchronize_remote} {x[0]}  {x[1]} \"' for x in self.synchronize_list])

    def run(self):
        return self._cmd(self.structure_synchronize())


if __name__ == '__main__':
    dirs = ((r'C:\Users\LCQ\Desktop\\', '/磁盘备份/Desktop/'),
            # (r'C:',)
            )
    log = 'D:/RobocopyLog/WinSCP_py.log'
    if os.path.exists(log): os.remove(log)
    a = BackupToUFile(dirs, _log=log, log_level='-1*')
    res = a.run()
    print(res)
